<template>
  <div class="main">
    <div class="icon thumb" @click="reduce" :style="{width:iconSize,height:iconSize}" v-show="showBtn">
      <img :src="publicUrl(`/images/step-reduce.png`)" />
    </div>
    <div class="num" v-show="!input">{{ num }}</div>
    <div class="num" v-show="input">
      <input
        @blur="inputBlur"
        class="input"
        v-model="num"
      />
    </div>
    <div class="icon thumb" @click="add" :style="{width:iconSize,height:iconSize}" v-show="showBtn">
      <img :src="publicUrl(`/images/step-add.png`)" />
    </div>
  </div>
</template>
<script setup lang="ts" name="">
import { ref, watch } from "vue";
import { publicUrl } from "@/utils/util";
interface Props {
  min?: number;               //计数器最小值
  max?: number;               //计数器最大值
  showBtn?:boolean;           //是否显示左右两个按钮
  iconSize?:string;           //icon大小
  input?: boolean;            //是否显示输入框可以修改
  step?: 1 | 0.1 | 0.01;      //step步数
  value?: number;             //计数器双向绑定值
}
const props = withDefaults(defineProps<Props>(), {
  min: undefined,
  max: undefined,
  input: true,
  placeholder:"",
  showBtn:true,
  iconSize:'0.2083rem',
  step: 1,
  value: 1,
});


const emits = defineEmits<{
  (event: "update:value", value: number|string): void;
}>();
const num = ref<number>(props.value === undefined ? 0 : props.value);

watch(
  () => props.value,
  (newValue) => {
    num.value = newValue;
  }
);
const inputBlur = () => {
  // console.log( num.value);
  num.value = Number( num.value.toString().replace(/\D/g,'') );
  if (
    num.value / props.step ===
    parseInt((num.value / props.step).toString())
  ) {

    //在区间中
    if (props.min !== undefined && num.value < props.min) num.value = props.min;
    else if (props.max !== undefined && num.value > props.max) num.value = props.max;
  }else{
     num.value = props.value;  //不在该区间内
  }
  emits("update:value", num.value);
};


const reduce = () => {
  let value: number =  Number(( num.value - props.step ).toFixed(2));
  if (props.min !== undefined && value < props.min) value = props.min;
  emits("update:value", value);
};

// const inputChange = ()=>{
//    if(num.value % props.step > 0 )
//    emits("update:value", num.value);
// }

const add = () => {
  let value: number = Number(( num.value + props.step ).toFixed(2));
  if (props.max !== undefined && value > props.max) value = props.max;
  emits("update:value", value);
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
